package com.stlm2.core;

import com.stlm2.core.memcached.MemcachedClient;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.util.StringUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;

public class AppConfig {

	static String configFileBase = null;

	/**
	 * 资源路径
	 */
	public static String RESOURCE_HOME = null;
	
	/**
	 * 资源文件名
	 */
	public static String RESOURCE_APP_ROOT = null;
	
	/**
	 * 域名
	 */
	public static String DOMAIN = null;

	/**
	 * IP
	 */
	public static String IP = null;

	/**
	 * 工程名
	 */
	public static String PROJECT_NAME = null;
	
	/**
	 * 全文检索URL
	 */
	public static String SOLR_URL = null;

	/**
	 * 客服电话
	 */
	public static String CUSTOMER_PHONE = null;


	/**
	 * 云通信URL
	 */
	public static String YUN_URL = null;

	/**
	 * 云通信主账户ID
	 */
	public static String YUN_ACCOUNT_SID = null;

	/**
	 * 云通信主账户token
	 */
	public static String YUN_AUTH_TOKEN = null;

	/**
	 * 云通信子账户ID
	 */
	public static String YUN_SUB_ACCOUNT_SID = null;

	/**
	 * 云通信子账户token
	 */
	public static String YUN_SUB_AUTH_TOKEN = null;

	/**
	 * 云通信app id
	 */
	public static String YUN_APP_ID = null;

    /**
     * 是否是测试环境
     */
    public static boolean IS_TEST = true;

    public static String DEALER_POST_TEMPLATE = "/static/images/honor.jpg";

	/**
	 * 分销商资质证书路径
	 */
	public static String DEALER_LICENSE_TEMPLATE = "";



	/**
	 * 应用在硬盘中的绝对路径
	 */
	static String webAppRoot = null;

	static String contextPath = null;

	/**
	 * 在一些不可控制的环境中,发布失败无法知道错误信息 所以,只能时之初始化成功后,才能通过相关页面查看
	 * 
	 * 在此,根据web.xml配置,可以避免发布失败,其方法是通过try catch,把错误信息存储在 该变量中,便于远程调试
	 */
	static String appConfigInitError = "";

	static String lastConfigError = "";

	static boolean appConfigInitSucc = false;

	private static Object locker = new Object();

	private static Element confRootEle = null;

	private static String appTitle = "Nvoyager";

	private static String appLang = "cn";

	private static String appCopyRight = "";

	// 资源文件域名
	private static String resourceDomain = "";

	static {
		// 缺省情况下的设定
		configFileBase = System.getProperties().getProperty("user.dir");
		// 如果在独立运行情况下,会被AppConfigFilter进行修改
		// 其目录为../WEB-INF/ 和web.xml在同一个目录下
	}

	public static String getConfigFileBase() {
		return configFileBase;
	}

	public static void setConfigFileBase(String fb) {
		configFileBase = fb.trim();
		configFileBase = configFileBase.replace('\\', '/');
		if (!configFileBase.endsWith("/"))
			configFileBase += "/";
	}

	/**
	 * 根据配置文件名称，获得对应的File对象 如果不存在，则返回null
	 * 
	 * @param conffn
	 * @return
	 */
	public static File getConfFile(String conffn) {
		String sysconffn = configFileBase + conffn;
		return new File(sysconffn);
	}

	public static Element loadConf() {
		if (confRootEle != null)
			return confRootEle;

		synchronized (locker) {
			if (confRootEle != null)
				return confRootEle;

			try {
				File f = getConfFile("zlg.xml");
				if (!f.exists()) {
					f = getConfFile("app.conf");
					if (!f.exists())
						f = getConfFile("app.conf.xml");
				}

				if (!f.exists())
					throw new RuntimeException(
							"no app.xml app.conf or app.conf.xml file found,last check file="
									+ f.getAbsolutePath());

				DocumentBuilderFactory docBuilderFactory = null;
				DocumentBuilder docBuilder = null;
				Document doc = null;

				// parse XML XDATA File
				docBuilderFactory = DocumentBuilderFactory.newInstance();
				docBuilderFactory.setValidating(false);
				docBuilder = docBuilderFactory.newDocumentBuilder();

				doc = docBuilder.parse(f);

				confRootEle = doc.getDocumentElement();

				appTitle = confRootEle.getAttribute("title");
				if (appTitle == null || appTitle.equals(""))
					appTitle = "Nvoyager";

				appCopyRight = confRootEle.getAttribute("copyright");
				if (appCopyRight == null)
					appCopyRight = "";

				appLang = confRootEle.getAttribute("lang");
				if (appLang == null || appLang.equals(""))
					appLang = "cn";

				resourceDomain = confRootEle.getAttribute("resource_domain");
				if (resourceDomain == null || resourceDomain.equals(""))
					resourceDomain = "";

				PROJECT_NAME = confRootEle.getAttribute("project_name");
				if (PROJECT_NAME == null || PROJECT_NAME.equals(""))
					PROJECT_NAME = "";


				loadInclude(docBuilder, f.getPath());
				
				return confRootEle;
			} catch (Exception e) {
				e.printStackTrace();

				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw);
				e.printStackTrace(pw);
				lastConfigError = e.getMessage() + "\r\n" + sw.toString();
				return null;
			}
		}
	}
	
	private static void loadInclude(DocumentBuilder docBuilder, String path){
		if(StringUtils.isNullOrTrimEmpty(path))
			return;
		
		try {
			File f = new File(path);

			if (!f.exists())
				return;
			Document doc = docBuilder.parse(f);
			confRootEle = doc.getDocumentElement();

			if(confRootEle.hasAttribute("resource_home"))
				RESOURCE_HOME = confRootEle.getAttribute("resource_home");
			
			if(confRootEle.hasAttribute("resource_root"))
				RESOURCE_APP_ROOT = confRootEle.getAttribute("resource_root");
			
			if(confRootEle.hasAttribute("domain"))
				DOMAIN = confRootEle.getAttribute("domain");

			if(confRootEle.hasAttribute("ip"))
				IP = confRootEle.getAttribute("ip");

			if(confRootEle.hasAttribute("solr_url"))
				SOLR_URL = confRootEle.getAttribute("solr_url");

			if(confRootEle.hasAttribute("customer_phone"))
				CUSTOMER_PHONE = confRootEle.getAttribute("customer_phone");

			if(confRootEle.hasAttribute("yun_url"))
				YUN_URL = confRootEle.getAttribute("yun_url");

			if(confRootEle.hasAttribute("yun_account_sid"))
				YUN_ACCOUNT_SID = confRootEle.getAttribute("yun_account_sid");

			if(confRootEle.hasAttribute("yun_auth_token"))
				YUN_AUTH_TOKEN = confRootEle.getAttribute("yun_auth_token");

			if(confRootEle.hasAttribute("yun_app_id"))
				YUN_APP_ID = confRootEle.getAttribute("yun_app_id");

            if(confRootEle.hasAttribute("test"))
                IS_TEST = BooleanUtils.toBoolean(NumberUtils.toInt(confRootEle.getAttribute("test")));

            if(confRootEle.hasAttribute("dealer_post_template"))
                DEALER_POST_TEMPLATE = confRootEle.getAttribute("dealer_post_template");

			if(confRootEle.hasAttribute("dealer_license_template"))
				DEALER_LICENSE_TEMPLATE = confRootEle.getAttribute("dealer_license_template");

			//微信
			Element wechatEle = getConfElement("wechat");
			if(wechatEle != null)
				WechatConfig.parse(wechatEle);

			//redis
			Element redisEle = getConfElement("redis");
			if (redisEle != null) {
				RedisClient.parse(redisEle);
			}


            // memcached
//            Element memcachedEle = getConfElement("memcached");
//            if(memcachedEle != null)
//                MemcachedClient.parse(memcachedEle);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String getAppTitle() {
		return appTitle;
	}

	/**
	 * 如果指定了资源文件目录就返回资源文件目录，否则返回当前工程所在目录
	 * 主要用于现网环境资源服务独立部署
	 * @return
	 */
	public static String getResourceHome() {
		if(RESOURCE_HOME != null)
			return RESOURCE_HOME;
		
		return getWebAppRoot();
	}

	public static String getContextPath() {
		return contextPath;
	}

	public static void setContextPath(String cxtPath) {
		contextPath = cxtPath;
	}

	public static String getWebAppRoot() {
		return webAppRoot;
	}

	public static void setWebAppRoot(String war) {
		webAppRoot = war;
	}

	public static Element getConfElement(String name) {
		NodeList nl = confRootEle.getElementsByTagName(name);
		if (nl == null)
			return null;

		return (Element) nl.item(0);
	}

}
